"""
Case Type   : python驱动psycopg2
Case Name   : sha256方式连接数据库，获取查询结果集
Create At   : 2024/3/29
Owner       : @ningyali
Description :
    1.解压openGauss-*-CentOS-x86_64-Python.tar.gz得到lib,替换psycopg2
    2.配置白名单
    3.配置lib
    4.连接数据库
    5.建表，插入数据
    6.获取查询结果集的一行
    7.获取查询结果集的指定行数
    8.获取全部结果集
    9.断开连接
Expect      :
    1.拷贝成功
    2.配置成功
    3.配置成功
    4.连接数据库成功
    5.执行成功
    6.查询成功，返回一行
    7.查询成功，返回指定行数
    8.查询成功，返回全部结果集
    9.执行成功
History     :
"""
import os
import unittest

from testcase.CONNECTORS.PDBC.PSYCOPG2. \
    Opengauss_Function_Connect_Psycopg_Common import Psycopg2Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class Psycopg55(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.conn_info = {'dbname': self.pri_sh.node.db_name,
                          'user': self.pri_sh.node.db_user,
                          'password': self.pri_sh.node.db_password,
                          'host': self.pri_sh.node.ssh_host,
                          'port': self.pri_sh.node.db_port}
        self.psycopg_com = Psycopg2Common(**self.conn_info)
        self.t_name = 't_psycopg55'

        text = '----前置操作: 备份白名单 expect: 备份成功----'
        self.log.info(text)
        res = self.psycopg_com.bak_conf(bak_flag=True)
        self.log.info(res)
        self.assertTrue(res, f'执行失败: {text}')

    def test_1(self):
        text = '----step1: 解压PDBC得到lib,替换psycopg2 expect: 执行成功----'
        res = self.psycopg_com.decompress_pkg()
        self.assertTrue(res, f'执行失败: {text}')
        res = self.psycopg_com.set_new_psycopg2()
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step2: 配置白名单 expect: 配置成功----'
        self.log.info(text)
        res = self.psycopg_com.set_pghba(open_flag=True)
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step3: 配置lib expect: 成功----'
        self.log.info(text)
        res = self.psycopg_com.set_lib_path()
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step4: 连接数据库 expect: 成功----'
        self.log.info(text)
        res = self.psycopg_com.conn_db()
        expect = f"user={self.pri_sh.node.db_user} " \
            f"dbname={self.pri_sh.node.db_name} " \
            f"host={self.pri_sh.node.ssh_host} " \
            f"port={self.pri_sh.node.db_port}"
        res = [self.assertIn(i, res) for i in expect.split()]
        self.assertEqual(len(res), 4, f'执行失败: {text}')

        text = '----step5: 建表，插入数据 expect: 成功----'
        self.log.info(text)
        sql = f"create table {self.t_name}(" \
              f"id integer,name varchar,detail text);"
        f_sql = self.psycopg_com.format_sql(sql)
        sql = f"insert into {self.t_name} values(%s,%s,%s);"
        v_list = [(1, 'aaa', 'a'), (2, 'bbb', 'b'), (3, 'ccc', 'c')]
        f_sql += self.psycopg_com.format_sql_with_executemany(sql, *v_list)
        run_sql = self.psycopg_com.join_run_sql(f_sql)
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertNotIn('ERROR', res, f'执行失败: {text}')

        text = '----step6: 获取查询结果集的一行 expect: 查询成功，返回一行----'
        self.log.info(text)
        f_sql = f'select * from {self.t_name};'
        run_sql = f'cur=conn.cursor()\n' \
                  f'cur.execute(\\"{f_sql}\\")\n' \
                  f'results = cur.fetchone()\n' \
                  f'print(results)\n' \
                  f'cur.close()\n'
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertIn(str(v_list[0]), res, f'执行失败: {text}')

        text = '----step7: 获取查询结果集的指定行数 expect: 查询成功，返回制定行数----'
        self.log.info(text)
        f_sql = f'select * from {self.t_name};'
        run_sql = f'cur=conn.cursor()\n' \
                  f'cur.execute(\\"{f_sql}\\")\n' \
                  f'results = cur.fetchmany(2)\n' \
                  f'print(results)\n' \
                  f'cur.close()\n'
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertIn(str(v_list[:2]), res, f'执行失败: {text}')

        text = '----step8: 获取全部结果集 expect: 查询成功，返回全部结果集----'
        self.log.info(text)
        f_sql = f'select * from {self.t_name};'
        run_sql = f'cur=conn.cursor()\n' \
                  f'cur.execute(\\"{f_sql}\\")\n' \
                  f'results = cur.fetchall()\n' \
                  f'print(results)\n' \
                  f'cur.close()\n'
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertIn(str(v_list), res, f'执行失败: {text}')

        text = '----step9: 删除表，断开连接 expect: 成功----'
        self.log.info(text)
        sql = f"drop table if exists {self.t_name}"
        f_sql = self.psycopg_com.format_sql(sql)
        run_sql = self.psycopg_com.join_run_sql(f_sql)
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertNotIn('ERROR', res, f'执行失败: {text}')

    def tearDown(self):
        text = '----run teardown----'
        self.log.info(text)

        text1 = f'----后置操作：删除解压文件目录----'
        self.log.info(text1)
        res1 = self.psycopg_com.clean_decompress_file()

        text2 = f'----后置操作：还原白名单----'
        self.log.info(text2)
        res2 = self.psycopg_com.bak_conf(bak_flag=False)

        self.assertTrue(res1, f'执行失败: {text1}')
        self.assertTrue(res2, f'执行失败: {text2}')

        text = f'-----{os.path.basename(__file__)} end-----'
        self.log.info(text)
